# coding=utf-8
import tornado.web

import WrapCursor
from CommonLib import *
from database.models.Controller import Controller
from database.models.DatabaseCommon import *
from database.models.SlaveID import SlaveID


class NameNewDeviceHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def ModBoardID(self, cur_id, tag):
        logging.debug('mod board id curid:%d, tag:%d' % (cur_id, int(tag)))
        to_board = [0xf0, 0x07, 81, 255, 111, 6, 1, 2, 0, 0]
        #           0    1  2   3     4   5  6  7  8  9
        send_id_1 = 0xf1
        send_id_2 = 7
        new_id_1 = (cur_id >> (8 * 1)) & 0xff
        new_id_2 = (cur_id >> (8 * 0)) & 0xff

        tag_value_all = int(tag)
        tag_1 = (tag_value_all >> (8 * 3)) & 0xff
        tag_2 = (tag_value_all >> (8 * 2)) & 0xff
        tag_3 = (tag_value_all >> (8 * 1)) & 0xff
        tag_4 = (tag_value_all >> (8 * 0)) & 0xff

        to_board[0] = send_id_1
        to_board[1] = send_id_2
        to_board[2] = tag_1
        to_board[3] = tag_2
        to_board[4] = tag_3
        to_board[5] = tag_4
        to_board[6] = new_id_1
        to_board[7] = new_id_2

        r = WrapCursor.WrapCursor()
        if global_status.ai_ele_global_status.config['with-hardwork']:
            sendWrap = SendWrap(device_listen_addr)
            sedret = sendWrap.SendData(to_board)
            if sedret is None or not sedret.ok:
                logging.error(str(sedret))
                return r.Error('change board  id error' + str(sedret))

            sedret = json.loads(sedret.text)
            if sedret['code'] is not 0:
                logging.error('retcode:%d' % sedret['code'])
                return r.Error('change board  id error')
        return ''

    def PickSlaveID(self):
        logging.debug('pick slave id:')

        s = Session()
        slav = s.query(SlaveID).order_by(-SlaveID.addr).all()

        if len(slav) is 0:
            cur_id = 100
        else:
            cur_id = slav[0].addr + 1
        s.close()
        return cur_id

    def post(self):
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            _ = ojson['id']
            _ = ojson['name']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error('request data error :' + str(e.message)))
            return
        logging.debug('begin deal name board,id:%d' % ojson['id'])
        session = Session()
        c = session.query(Controller).filter_by(id=ojson['id']).all()
        if len(c) != 1:
            self.write(r.Error('从机id不存在'))
            return
        # session.commit()
        if c[0].Name == u'' or c[0].Name == '':
            cur_id = self.PickSlaveID()
            ss = Session()
            newSlav = SlaveID(addr=cur_id)
            ss.add(newSlav)
            ss.commit()
            ss.close()
            ret = self.ModBoardID(cur_id, c[0].tag)
            if ret is not '':
                logging.error('mod boardid error')
                self.write(ret)
                return
            logging.debug('mod board name')
            new_data = {'Name': ojson['name'], 'HardID': cur_id}
            s2 = Session()

            cnt = s2.query(Controller).filter(Controller.id == int(ojson['id'])).update(new_data)
        else:
            c[0].Name = ojson['name']
        try:
            session.commit()
            s2.commit()
            s2.close()
            logging.debug('mod name ok')
        except Exception as e:
            logging.warn('commit error' + e.message)

        retjson = dict()
        retjson['Code'] = 0
        retjson['desc'] = '修改成功'
        self.write(json.dumps(retjson))
